package com.bhs.sansonglogistics.ui.enterprise;

import static com.google.android.material.tabs.TabLayout.MODE_SCROLLABLE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.base.Constants;
import com.bhs.sansonglogistics.bean.CompanyCollect;
import com.bhs.sansonglogistics.bean.MenuBean;
import com.bhs.sansonglogistics.bean.OperationEvent;
import com.bhs.sansonglogistics.bean.TabBean;
import com.bhs.sansonglogistics.bean.event.CompanyInfo;
import com.bhs.sansonglogistics.dialog.BottomSelectListDialog;
import com.bhs.sansonglogistics.dialog.BottomTypeDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.dialog.SharePosterDialog;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.home.FragmentAdapter;
import com.bhs.sansonglogistics.ui.home.OrderGoodsListFragment;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.utils.WxShareUtils;
import com.bhs.sansonglogistics.view.SelectedFont;
import com.bhs.sansonglogistics.view.SelectedFont2;
import com.bhs.sansonglogistics.view.SelectedFont3;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.luck.picture.lib.utils.PictureFileUtils;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 公司详情
 */
public class CompanyDetailsActivity extends BaseActivity implements View.OnClickListener, NetCallBack {


    private TabLayout mTabLayout;
    private ViewPager2 mViewPage;
    private String[] tabs = {"公司资料", "专线信息", "评论"};
    private int logistics_id;
    private LinearLayout mLlOperation;
    private TextView mTvNavigation;
    private TextView mTvCollect;
    private TextView mTvService;
    private TextView mTvContactImmediately;
    private Drawable collectYellow;
    private Drawable collect;
    private Bitmap bmp;

    @Override
    public int initLayout() {
        return R.layout.activity_company_details;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        logistics_id = getIntent().getIntExtra("logistics_id", 0);
        mTabLayout = findViewById(R.id.tabLayout);
        mViewPage = findViewById(R.id.view_page);
        mLlOperation = findViewById(R.id.ll_operation);
        mTvNavigation = findViewById(R.id.tv_navigation);
        mTvCollect = findViewById(R.id.tv_collect);
        mTvService = findViewById(R.id.tv_service);
        mTvContactImmediately = findViewById(R.id.tv_contact_immediately);
        mTvNavigation.setOnClickListener(this);
        mTvCollect.setOnClickListener(this);
        mTvService.setOnClickListener(this);
        mTvContactImmediately.setOnClickListener(this);
        collectYellow = getResources().getDrawable(R.mipmap.ic_collect_yellow, null);
        collect = getResources().getDrawable(R.mipmap.ic_collect, null);
        collectYellow.setBounds(0, 0, collectYellow.getMinimumWidth(), collectYellow.getMinimumHeight());
        collect.setBounds(0, 0, collect.getMinimumWidth(), collect.getMinimumHeight());
        findViewById(R.id.fl_share).setOnClickListener(this);
    }

    @Override
    public void initData() {
        if (logistics_id > 0) {
            mLlOperation.setVisibility(View.VISIBLE);
        } else {
            mLlOperation.setVisibility(View.GONE);
            logistics_id = SharedPreferencesUtils.getInt(mActivity, "logistics_id", 0);
        }
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        //tab切换时候的字体设置
        mTabLayout.addOnTabSelectedListener(new SelectedFont2(this));
        ArrayList<BaseFragment> fragments = new ArrayList<>();
        fragments.add(CompanyProfileFragment.newInstance(logistics_id));
        fragments.add(PrivateLineInformationFragment.newInstance(logistics_id));
        fragments.add(CompanyEvaluationFragment.newInstance(logistics_id));
        mViewPage.setOffscreenPageLimit(fragments.size());
        mViewPage.setAdapter(new FragmentAdapter(this, fragments));
        new TabLayoutMediator(mTabLayout, mViewPage, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(tabs[position]);
            }
        }).attach();
        mViewPage.setCurrentItem(getIntent().getIntExtra("item", 0));
        mViewPage.setUserInputEnabled(false);
    }

    private CompanyInfo companyInfo;

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(CompanyInfo event) {
        mTabLayout.getTabAt(2).setText(String.format("评价(%s)", event.getComment_num()));
        companyInfo = event;
        Glide.with(mContext)
                .asBitmap()
                .load(event.getCompany_pic())
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        if (resource.getHeight() > 500 && resource.getWidth() > 500) {
                            bmp = Bitmap.createScaledBitmap(resource, 500, 500, true);
                        } else {
                            bmp = resource;
                        }
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_navigation:
                bottomSelect();
                break;
            case R.id.tv_collect:
                if ((int) mTvCollect.getTag() == 0) {
                    mTvCollect.setCompoundDrawables(null, collectYellow, null, null);
                } else {
                    mTvCollect.setCompoundDrawables(null, collect, null, null);
                }
                networkRequest(netApi.click_collect(logistics_id), this);
                break;
            case R.id.tv_service:
                if (TextUtils.isEmpty(companyInfo.getSearch_phone())) {
                    ToastUtil.show("暂无客服");
                    return;
                }
                MyUtils.callPhone(mActivity, companyInfo.getSearch_phone());
                break;
            case R.id.tv_contact_immediately:
                EventBus.getDefault().post(new OperationEvent("立即联系"));
                break;
            case R.id.fl_share:
                if (companyInfo == null) {
                    return;
                }
                BottomTypeDialog bottomTypeDialog = new BottomTypeDialog(mActivity);
                bottomTypeDialog.show();
                bottomTypeDialog.setMyClickListener(new MyClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.tv_business_license) {
                            WxShareUtils.shareMiniPro(mActivity, "/page_order/companyDetails/index?logistics_id=" + logistics_id, companyInfo.getCompany_name(), "测试内容", bmp);
                        } else {
                            SharePosterDialog sharePosterDialog = new SharePosterDialog(mActivity, companyInfo, logistics_id);
                            new XPopup.Builder(mActivity)
                                    .isLightStatusBar(false)
                                    .asCustom(sharePosterDialog)
                                    .show();
                        }
                    }
                });

                break;
        }
    }

    private BottomSelectListDialog listDialog;

    private void bottomSelect() {
        if (listDialog == null) {
            List<MenuBean> list = new ArrayList<>();
            list.add(new MenuBean("百度地图"));
            list.add(new MenuBean("高德地图"));
            list.add(new MenuBean("取消"));
            listDialog = new BottomSelectListDialog(mActivity, list);
            listDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    EventBus.getDefault().post(new OperationEvent(id));
                }
            });
        }
        listDialog.show();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        BaseBean bean = new Gson().fromJson(json, BaseBean.class);
        if (bean.getCode().equals("1")) {
            if ((int) mTvCollect.getTag() == 0) {
                ToastUtil.show("收藏成功");
                mTvCollect.setTag(1);
            } else {
                mTvCollect.setTag(0);
            }

        } else {
            if ((int) mTvCollect.getTag() == 1) {
                mTvCollect.setCompoundDrawables(null, collectYellow, null, null);
            } else {
                mTvCollect.setCompoundDrawables(null, collect, null, null);
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Subscribe
    public void onEvent(CompanyCollect event) {
        mTvCollect.setTag(event.getIs_collect());
        if (event.getIs_collect() == 1) {
            mTvCollect.setCompoundDrawables(null, collectYellow, null, null);
        } else {
            mTvCollect.setCompoundDrawables(null, collect, null, null);
        }
    }
}